from sqlalchemy.orm import Session
import json
from typing import List
from app.entity import SysPost
from app.schema import PostData
from utils.request import PageInfo

class PostModel:
    """
    菜单管理模块数据库操作层
    """
    @classmethod
    def get_select_options(cls, db: Session):
        opts = db.query(SysPost).filter(SysPost.status==0).all()
        
        return opts

    @classmethod
    def insert(cls, db: Session, data: PostData):
        db_post = SysPost(**data.dict())
        db.add(db_post)
        db.commit()
        return True
    

    @classmethod
    def edit(cls, db: Session, post: dict):
        db.query(SysPost).filter(SysPost.post_id == post.get('post_id')).update(post)
        db.commit()

    @classmethod
    def delete(cls, db: Session, ids: List[int]):
        db.query(SysPost).filter(SysPost.post_id.in_(ids)).delete()
        db.commit()

    @classmethod
    def get_by_id(cls, db: Session, id: int):
        return db.query(SysPost).filter(SysPost.post_id==id).first()
        

    @classmethod
    def get_page(cls, db: Session, where:dict, page: PageInfo ):
        total = db.query(SysPost).filter_by(**where).count()
        rows  = db.query(SysPost).filter_by(**where).offset((page.page-1)*page.limit).limit(page.limit).all()
        
        return total, rows
        